<template>
  <div>
    <a-modal
      v-model="tabVisible"
      title="批量导入SKU"
      @ok="handleOk"
      @cancel="cancel"
      okText="确定导入"
      cancelText="取消导入"
      width="85%"
    >
      <div slot="footer">
        <a-button @click="cancel"> 取消 </a-button>
        <a-button type="primary" @click="handleOk" :loading="loading">
          确定导入
        </a-button>
      </div>
      <a-upload
        name="file"
        :multiple="true"
        :action="baseUrl + `/by-sku/upLoad`"
        :headers="headers"
        accept=".xlsx,.xls"
        style="margin-right: 20px"
        @change="handleChange"
        :fileList="fileList"
      >
        <a-button
          style="
            background: #409cff;
            color: #ffff;
            border: none;
            margin-bottom: 20px;
          "
        >
          <a-icon type="upload" /> 选择文件
        </a-button>
      </a-upload>
      <div style="margin-bottom: 20px">
        <span>
          <a-button type="primary" class="top-btn" @click="batchSKUType">
            批量更改分类
          </a-button>
        </span>
        <span v-if="batchSKUTypeFlag" style="margin-left: 10px"
          >产品分类：
          <a-cascader
            style="width: 200px; margin-right: 20px"
            :options="platformOptions"
            :show-search="{ filter }"
            placeholder="请选择分类"
            @change="onPlatformOptionsChange"
        /></span>
        <!-- <span v-if="batchSKUTypeFlag"
          >自有分类：
          <a-cascader
            style="width: 200px"
            :options="freedomOptions"
            :show-search="{ filter }"
            placeholder="请选择分类"
            @change="onFreedomOptionsChange"
        /></span> -->
        <a-button
          v-if="batchSKUTypeFlag"
          @click="saveBatchSKUType"
          type="primary"
          style="
            background: #409cff;
            color: #ffff;
            border: none;
            margin-left: 20px;
          "
        >
          保存
        </a-button>
      </div>
      <div style="color: red">注：带*号为必填项 长宽高最大值为274！</div>
      <!-- 表格 -->
      <a-table
        size="small"
        bordered
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
        :data-source="dataSource"
        :pagination="false"
      >
        <a-table-column key="sku" data-index="sku">
          <span slot="title"> <span style="color: red">*</span>产品SKU</span>
          <!-- 产品SKU -->
          <template slot-scope="text, record">
            <a-input
            :maxLength="128"
              :style="!record.sku ? styleBack : styleYes"
              v-model="record.sku"
            />
          </template>
        </a-table-column>
        <a-table-column
          key="platformClassifyName"
          data-index="platformClassifyName"
        >
          <span slot="title"> <span style="color: red">*</span>产品分类</span>
          <template slot-scope="text, record">
            <a-input
            :maxLength="128"
              :style="!record.platformClassifyName ? styleBack : styleYes"
              v-model="record.platformClassifyName"
            />
          </template>
        </a-table-column>
        <!-- <a-table-column key="selfClassifyName" data-index="selfClassifyName">
          <span slot="title">自有分类</span>
          <template slot-scope="text, record">
            <a-input v-model="record.selfClassifyName" />
          </template>
        </a-table-column> -->
        <a-table-column key="chineseName" data-index="chineseName">
          <span slot="title">
            <span style="color: red">*</span> 产品中文名</span
          >
          <template slot-scope="text, record">
            <a-input
            :maxLength="128"
              :style="
                !record.chineseName ||
                !/.*[\u4e00-\u9fa5]+.*$/.test(record.chineseName)
                  ? styleBack
                  : styleYes
              "
              v-model="record.chineseName"
            />
          </template>
        </a-table-column>
        <a-table-column key="englishName" data-index="englishName">
          <span slot="title"><span style="color: red">*</span>产品英文名</span>
          <template slot-scope="text, record">
            <a-input
            :maxLength="128"
              :style="
                !record.englishName ||
                /.*[\u4e00-\u9fa5]+.*$/.test(record.englishName)
                  ? styleBack
                  : styleYes
              "
              v-model="record.englishName"
            />
          </template>
        </a-table-column>

        <!-- <a-table-column key="tagDefault" data-index="tagDefault">
          <span slot="title">标签类型</span>
           SKU类型
          <template slot-scope="text, record">
            <a-select
              default-value="1"
              style="width: 120px"
              v-model="record.tagDefault"
            >
              <a-select-option value="1"> 系统默认标签 </a-select-option>
              <a-select-option value="2"> 自定义标签 </a-select-option>
            </a-select>
           <a-input v-model="zdybq" v-if="" />
          </template>
        </a-table-column> -->
        <a-table-column key="packingType" data-index="packingType">
          <span slot="title"><span style="color: red">*</span>包装类型</span>
          <!-- SKU包装类型 -->
          <template slot-scope="text, record">
            <a-select
              :style="!record.packingType ? styleBack : styleYes"
              style="width: 120px"
              v-model="record.packingType"
              default-value="106"
            >
              <a-select-option
                :value="item.key"
                v-for="item in tagType"
                :key="item.key"
              >
                {{ item.title }}
              </a-select-option>
            </a-select>
          </template>
        </a-table-column>
        <a-table-column key="long" data-index="long">
          <span slot="title"> <span style="color: red">*</span>长(cm)</span>
          <!-- 长(cm) -->
          <template slot-scope="text, record">
            <a-input-number
              :min="0"
              :precision="2"
              :style="
                !record.long || record.long * 1 > 274 ? styleBack : styleYes
              "
              v-model="record.long"
            />
          </template>
        </a-table-column>
        <a-table-column key="width" data-index="width">
          <span slot="title"> <span style="color: red">*</span>宽(cm)</span>
          <!-- 宽(cm) -->
          <template slot-scope="text, record">
            <a-input-number
              :min="0"
              :precision="2"
              :style="
                !record.width || record.width * 1 > 274 ? styleBack : styleYes
              "
              v-model="record.width"
            />
          </template>
        </a-table-column>
        <a-table-column key="height" data-index="height">
          <span slot="title"> <span style="color: red">*</span>高(cm)</span>
          <!-- 高(cm) -->
          <template slot-scope="text, record">
            <a-input-number
              :min="0"
              :precision="2"
              :style="
                !record.height || record.height * 1 > 274 ? styleBack : styleYes
              "
              v-model="record.height"
            />
          </template>
        </a-table-column>

        <a-table-column key="weight" data-index="weight">
          <span slot="title"> <span style="color: red">*</span>重量(g)</span>
          <!-- 重量 -->
          <template slot-scope="text, record">
            <a-input-number
              :style="!record.weight ? styleBack : styleYes"
              :min="0"
              :precision="2"
              v-model="record.weight"
            />
          </template>
        </a-table-column>

        <a-table-column key="customsCode" data-index="customsCode">
          <span slot="title">海关编码</span>
          <!-- 海关编码 -->
          <template slot-scope="text, record">
            <a-input :maxLength="128" v-model="record.customsCode" />
          </template>
        </a-table-column>
        <a-table-column key="declaredValue" data-index="declaredValue">
          <span slot="title"
            ><span style="color: red">*</span>申报价值(USD)</span
          >
          <!-- 申报价值 -->
          <template slot-scope="text, record">
            <a-input-number
              :style="!record.declaredValue ? styleBack : styleYes"
              :precision="2"
              v-model="record.declaredValue"
            />
          </template>
        </a-table-column>
        <a-table-column
          key="operation"
          data-index="operation"
          title="操作"
          width="55px"
        >
          <template slot-scope="text, record">
            <a-popconfirm
              v-if="dataSource && dataSource.length"
              title="确定删除吗?"
              okText="确定"
              cancelText="取消"
              @confirm="() => onDelete(record.key)"
            >
              <a href="javascript:;">删除</a>
            </a-popconfirm>
          </template>
        </a-table-column>
      </a-table>
    </a-modal>
  </div>
</template>

<script>
import baseUrl from "@/utils/baseUrl";
import req from "@/utils/req";
import {
  SKU_tgasType,
  SKU_upLoadBatchSave,
  // SKU_batchClassify,
  SKU_TypeTree,
} from "@/apis/clientSide/SKUManage/SKUList";
export default {
  props: ["getTableData"],
  async created() {
    let { code, responseBody } = await SKU_tgasType({
      tagType: 3,
    });
    if (code === "200") {
      this.tagType = responseBody;
    }
    let res = await SKU_tgasType({
      tagType: 1,
    });
    if (res.code === "200") {
      this.platformClassifyName = res.responseBody;
    }
  },
  mounted() {
    this.$bus.$off("SkuIncShowModel");
    this.$bus.$on("SkuIncShowModel", () => {
      this.fileList = [];
      this.dataSource = [];
      setTimeout(() => {
        this.tabVisible = true;
      }, 100);
    });
    // 获取分类
    this.getBatchSKUTypeTree();
    //获取表格数据
    this.getTableData();
  },
  data() {
    return {
      styleBack: {
        border: "1px solid #f00",
        borderRadius: "5px",
      },
      styleYes: {
        border: "1px solid #ccc",
        borderRadius: "5px",
      },
      loading: false,
      // 自有分类 用户建立的分类
      selfClassify: "",
      // 分类框显示隐藏
      batchSKUTypeFlag: false,
      fileList: [],
      flag: false,
      // 产品分类
      platformClassifyName: [],
      baseUrl,
      tabVisible: false,
      headers: {
        authorization: "authorization-text",
        token: sessionStorage.getItem("tk"),
      },
      dataSource: [],
      //包装类型
      tagType: [],
      upTableData: {
        //   中文名称
        chineseName: "",
        //   海关编码
        customsCode: null,
        //   申报价值
        declaredValue: null,
        //   英文名称
        englishName: "",
        //   高
        height: 0,
        //   长
        long: 0,
        //   包装类型
        packingTypeName: "",
        //   平台分类
        platformClassifyName: "",
        //   自有分类
        selfClassifyName: "",
        //   产品标签系统默认生成（暂定8位）|
        productTag: "",
        //   sku
        sku: "",
        //   主键
        skuId: 0,
        //   标签默认类型
        tagDefault: 0,
        //   重量
        weight: 0,
        //    宽
        width: 0,
      },
      //平台分类树1
      platformOptions: [],
      platformArray: [],
      freedomOptions: [],
      //表格选中提交后台数组
      tablecheckedArray: [],
      selectedRowKeys: [],
      unitOption: [
        { value: "0", label: "cm" },
        { value: "1", label: "in" },
      ],
      weightOption: [
        { value: "0", label: "g" },
        { value: "1", label: "lb" },
      ],
    };
  },
  methods: {
    changeWeight() {},
    changeUnit() {},
    cancel() {
      this.tabVisible = false;
      setTimeout(() => {
        this.fileList = [];
      }, 50);
    },
    //平台分类改变
    onPlatformOptionsChange(value, option) {
      this.platformArray = value;
      if (option && option[0].label) {
        this.platformClassifyName = option[0].label;
      } else {
        this.platformClassifyName = "";
      }
    },
    //自由分类改变
    onFreedomOptionsChange(value, option) {
      this.freedomArray = value;
      this.selfClassifyName = option[0].label;
    },
    //获取批量分类数据
    async getBatchSKUTypeTree() {
      let { code, responseBody } = await SKU_TypeTree({
        tagType: 1,
        isDisable: 0,
        isChild: true,
      });
      if (code === "200") {
        this.platformOptions = req.treeDatas(responseBody);
      }
      let res = await SKU_TypeTree({
        tagType: 2,
        isDisable: 0,
        isChild: true,
      });
      if (res.code === "200") {
        this.freedomOptions = req.treeDatas(res.responseBody);
      }
    },

    //批量更改SKU分类
    batchSKUType() {
      this.batchSKUTypeFlag = true;
    },
    //保存批量分类信息
    async saveBatchSKUType() {
      if (this.platformClassifyName == "") {
        this.$message.error("请选择平台分类");
      }
      if (!this.tablecheckedArray || this.tablecheckedArray.length <= 0) {
        this.$message.error("请勾选需更改分类的数据");
        return false;
      }
      this.tablecheckedArray.forEach((item) => {
        if (this.platformArray) {
          item.platformClassify = this.platformArray.join(",");
        }
        if (this.freedomArray) {
          item.selfClassify = this.freedomArray.join(",");
        }
        item.platformClassifyName = this.platformClassifyName;
        item.selfClassifyName = this.selfClassifyName;
      });

      // let { code } = await SKU_batchClassify(this.tablecheckedArray);
      // if (code == "10000") {
      //   console.log(this.dataSource);
      //   this.dataSource.forEach(item => {
      //     item.platformClassifyName = this.platformClassifyName;
      //     item.selfClassifyName = this.selfClassifyName;
      //   });
      //   this.getTableData();
      this.platformClassifyName = "";
      this.selfClassifyName = "";
      this.batchSKUTypeFlag = false;
      // }
    },
    //点击确定
    async handleOk() {
      this.loading = true;
      if (!this.dataSource || this.dataSource.length === 0) {
        this.$message.error("请上传文件后保存！");
        return false;
      }
      let chineseFlag = true;
      let englishFlag = true;
      let longFlag = true;
      this.flag = true;
      this.dataSource.forEach((item) => {
        if (
          item.platformClassifyName === null ||
          item.platformClassifyName === ""
        ) {
          this.flag = false;
        }
        if (item.chineseName === null || item.chineseName === "") {
          this.flag = false;
        }
        if (item.sku === null || item.sku === "") {
          this.flag = false;
        }
        if (item.long === null || item.long === "") {
          this.flag = false;
        }
        if (item.width === null || item.width === "") {
          this.flag = false;
        }
        if (item.height === null || item.height === "") {
          this.flag = false;
        }
        if (item.long * 1 > 274) {
          longFlag = false;
        }
        if (item.width * 1 > 274) {
          longFlag = false;
        }
        if (item.height * 1 > 274) {
          longFlag = false;
        }
        if (!/.*[\u4e00-\u9fa5]+.*$/.test(item.chineseName)) {
          chineseFlag = false;
        }
        if (/.*[\u4e00-\u9fa5]+.*$/.test(item.englishName)) {
          englishFlag = false;
        }
        if (item.weight === null || item.weight === "") {
          this.flag = false;
        }
        if (item.declaredValue == null || item.declaredValue == "") {
          this.flag = false;
        }
        // if (item.customsCode == null || item.customsCode == "") {
        //   this.flag = false;
        //   return false;
        // }
        if (item.englishName == null || item.englishName == "") {
          this.flag = false;
        }
        if (item.packingType == null || item.packingType == "") {
          this.flag = false;
        }
      });
      if (this.flag === true) {
        if (chineseFlag) {
          if (englishFlag) {
            if (longFlag) {
              let { code } = await SKU_upLoadBatchSave(this.dataSource);
              if (code === "10000") {
                this.getTableData();
                this.tabVisible = false;
                this.loading = false;
              } else {
                this.loading = false;
              }
            } else {
              this.loading = false;
              this.$message.error("存在长宽高度不合格的数据，请修改！");
              return false;
            }
          } else {
            this.loading = false;
            this.$message.error("商品英文名不允许输入汉字！");
            return false;
          }
        } else {
          this.loading = false;
          this.$message.error("商品中文名必须包含汉字！");
          return false;
        }
      } else {
        this.loading = false;
        this.$message.error("必填项缺失！");
        return false;
      }
    },
    // 上传文件
    handleChange(info) {
      this.fileList = info.fileList;
      this.tablecheckedArray = [];
      this.selectedRowKeys = [];
      this.dataSource = [];
      if (info.fileList && info.fileList.length >= 2) {
        this.fileList = info.fileList;
        info.fileList = info.fileList.splice(0, 1);
        this.$message.warning("只能上传一个文件！");
      }
      if (info.file.status === "done") {
        this.$message.success(`${info.file.name} 导入成功！`);
        let { response } = info.fileList[0];
        if (response.responseBody && response.responseBody.length >= 1) {
          response.responseBody.forEach((item) => {
            if (item.packingType === "-1") {
              item.packingType = "106";
            }
            if (item.tagDefault === null || item.tagDefault === "") {
              item.tagDefault = "1";
            }
          });
          response.responseBody.forEach((item) => {
            if (item.productTag != null) {
              item.tagDefault = "2";
            }
          });
        }
        this.dataSource = response.responseBody;
      } else if (info.file.status === "error") {
        this.$message.error(`${info.file.name} 导入失败，请稍后再试！`);
      }
    },
    //搜索框过滤搜索
    filter(inputValue, path) {
      return path.some(
        (option) =>
          option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
      );
    },
    //表格删除当前行
    onDelete(key) {
      const dataSource = [...this.dataSource];
      this.dataSource = dataSource.filter((item) => item.key !== key);
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.tablecheckedArray = selectedRows;
      this.selectedRowKeys = selectedRowKeys;
    },
  },
};
</script>

<style lang="less" scoped></style>
